﻿using System;
using System.ComponentModel.Composition;
using Microsoft.Practices.ServiceLocation;
using Ninject;
using NinjectAdapter;
using Reactor.Configuration;
using Reactor.Contracts;
using Reactor.Environment;

namespace Reactor.Container.Ninject
{
    [Export(typeof(ICustomizeReactorInitialization))]
    public class ContainerCustomizer : ICustomizeReactorInitialization
    {
        #region Fields

        private readonly IKernel _kernel;
        private IServiceLocator _serviceLocator;

        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="ContainerCustomizer"/> class.
        /// <remarks>This constructor will create a new instance of <seealso cref="StandardKernel"/> 
        /// and pass it into the constructor overload that accepts an <seealso cref="IKernel"/> instance.</remarks>
        /// </summary>
        public ContainerCustomizer() : this(new StandardKernel()){}

        /// <summary>
        /// Initializes a new instance of the <see cref="ContainerCustomizer"/> class.
        /// </summary>
        /// <param name="kernel">The kernel.</param>
        public ContainerCustomizer(IKernel kernel)
        {
            if (kernel == null) throw new ArgumentNullException("kernel");

            _kernel = kernel;
        }

        #endregion

        #region Implementation of ICustomizeReactorInitialization

        /// <summary>
        /// Gets the execution order for this initializer. The lower the value, the earlier it will 
        /// be executed in a chain of initializers.
        /// </summary>
        /// <value>The execution order.</value>
        public uint ExecutionOrder
        {
            get { return 0; }
        }

        /// <summary>
        /// Initializes Reactor by providing a Windsor based <seealso cref="IServiceRegistrar"/> and <seealso cref="IServiceLocator"/>.
        /// </summary>
        public void InitializeReactor()
        {
            var ninjectServiceRegistrar = new NinjectServiceRegistrar(_kernel);

            // Set platform service locator
            if (_serviceLocator == null) _serviceLocator = new NinjectServiceLocator(_kernel);
            Context.ServiceLocator = _serviceLocator;

            ninjectServiceRegistrar.RegisterInstance<IServiceRegistrar>(ninjectServiceRegistrar);
        }

        #endregion
    }
}
